<script setup lang="ts">
import TreeSubMenu from './TreeSubMenu.vue'
import { RouteRecordRaw, useRouter } from 'vue-router'
import { createVNode } from 'vue'
interface Props {
  routes?: RouteRecordRaw[]
}
const router = useRouter()
const props = withDefaults(defineProps<Props>(), {
  routes: () => [],
})
const getAllRoutes = router.getRoutes().filter((item) => {
  return item.meta.type === 'menu'
})
const r = props.routes.length === 0 ? getAllRoutes : props.routes
function handleToRouter(path: string) {
  if (path.startsWith('/')) {
    router.push({ path })
  } else {
    router.push({ path: '/' + path })
  }
}
function renderIcons(name: string) {
  let i = resolveComponent(name)
  return createVNode(i)
}
</script>
<template>
  <template v-for="(item, index) in r" :key="index">
    <template v-if="item.children && item.children?.length > 0">
      <ElSubMenu class="menu-sub-item" :key="index" :index="item.path">
        <template #title>
          <component v-if="item?.meta?.icon" :is="renderIcons(item?.meta?.icon as string)"></component>
          <span>{{ item?.meta?.title }}</span>
        </template>
        <TreeSubMenu v-if="item.children" :routes="item.children"></TreeSubMenu>
      </ElSubMenu>
    </template>
    <template v-else>
      <ElMenuItem class="menu-item-wrapper" @click="handleToRouter(item.path)" :key="index" :index="item.path">
        <component v-if="item?.meta?.icon" :is="renderIcons(item?.meta?.icon as string)"></component>
        <span>{{ item?.meta?.title }}</span>
      </ElMenuItem>
    </template>
  </template>
</template>
<style lang="scss" scoped>
.menu-sub-item {
  ::v-deep(.el-sub-menu__title) {
    padding-right: 20px;
    svg {
      width: 1em;
      height: 1em;
      font-size: 14px;
    }
    span {
      margin-left: 10px;
      font-size: 16px;
    }
  }
}
.menu-item-wrapper {
  display: flex;
  align-items: center;

  > svg {
    width: 1em;
    height: 1em;
    font-size: 14px;
  }
  > span {
    margin-left: 10px;
    font-size: 16px;
  }
}
</style>
